﻿using Bridge.Workflow.Models;
using Bridge.Workflow.Roles.Dto;
using Bridge.Workflow.Users.Dto;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Threading.Tasks;
using Volo.Abp.AspNetCore.Mvc;

namespace Bridge.Workflow.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    [Route("api/v1/Workflow/TokenAuth/[action]")]
    public class TokenAuthController : AbpController
    {
        private readonly IUserAppService _logInManager;

        public TokenAuthController(IUserAppService logInManager)
        {
            _logInManager = logInManager;
        }

        /// <summary>
        /// 登录认证
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<AuthenticateResultModel>> Authenticate([FromBody] AuthenticateModel model)
        {
            var token = await _logInManager.Authenticate(new Users.Request.UserLoginInfoRequest
            {
                UserNameOrEmailAddress = model.UserNameOrEmailAddress,
                Password = model.Password,
                RememberMe = model.RememberClient
            });

            if (string.IsNullOrEmpty(token))
            {
                return Response<AuthenticateResultModel>.Fail("登录失败");
            }

            var jwtTokenHandler = new JwtSecurityTokenHandler();
            var jwtToken = jwtTokenHandler.ReadJwtToken(token);


            return Response<AuthenticateResultModel>.Success(new AuthenticateResultModel
            {
                AccessToken = token,
                EncryptedAccessToken = jwtToken.SignatureAlgorithm,
                ExpireInSeconds = (int)jwtToken.ValidTo.TimeOfDay.TotalSeconds,
                UserId = jwtToken.Subject
            });
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public async Task<Response<UserDto>> GetAsync(string userId)
        {
            var result = await _logInManager.GetAsync(userId);
            if (result.Code == 0)
            {
                return Response<UserDto>.Fail(result.Message);
            }

            return Response<UserDto>.Success(result.Result);
        }

        /// <summary>
        /// 获取当前登录信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public Response<GetCurrentLoginInformationsOutput> GetCurrentLoginInformations()
        {
            var result = _logInManager.GetCurrentLoginInformations();
            if (result.Code == 0)
            {
                return Response<GetCurrentLoginInformationsOutput>.Fail(result.Message);
            }

            return Response<GetCurrentLoginInformationsOutput>.Success(result.Result);
        }

        /// <summary>
        /// 获取所有角色
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public async Task<Response<List<RoleDto>>> GetRoles(SearchUserInput input)
        {
            var result = await _logInManager.GetRoles(input);
            if (result.Code == 0)
            {
                return Response<List<RoleDto>>.Fail(result.Message);
            }

            return Response<List<RoleDto>>.Success(result.Result);
        }

        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public async Task<Response<List<UserDto>>> GetUser(SearchUserInput input)
        {
            var result = await _logInManager.GetUser(input);
            if (result.Code == 0)
            {
                return Response<List<UserDto>>.Fail(result.Message);
            }

            return Response<List<UserDto>>.Success(result.Result);
        }
        //[HttpGet]
        //public List<ExternalLoginProviderInfoModel> GetExternalAuthenticationProviders()
        //{
        //    return ObjectMapper.Map<List<ExternalLoginProviderInfoModel>>(_externalAuthConfiguration.Providers);
        //}

        // [HttpPost]
        //public async Task<ExternalAuthenticateResultModel> ExternalAuthenticate([FromBody] ExternalAuthenticateModel model)
        //{
        //    var externalUser = await GetExternalUserInfo(model);

        //    var loginResult = await _logInManager.LoginV2(new Account.Request.UserLoginInfoRequest
        //    {
        //        Phone = model.AuthProvider,
        //        Password = model.ProviderKey
        //    });

        //    switch (loginResult.Result)
        //    {
        //        case AbpLoginResultType.Success:
        //            {
        //                var accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity));
        //                return new ExternalAuthenticateResultModel
        //                {
        //                    AccessToken = accessToken,
        //                    EncryptedAccessToken = GetEncryptedAccessToken(accessToken),
        //                    ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds
        //                };
        //            }
        //        case AbpLoginResultType.UnknownExternalLogin:
        //            {
        //                var newUser = await RegisterExternalUserAsync(externalUser);
        //                if (!newUser.IsActive)
        //                {
        //                    return new ExternalAuthenticateResultModel
        //                    {
        //                        WaitingForActivation = true
        //                    };
        //                }

        //                // Try to login again with newly registered user!
        //                loginResult = await _logInManager.LoginAsync(new UserLoginInfo(model.AuthProvider, model.ProviderKey, model.AuthProvider), GetTenancyNameOrNull());
        //                if (loginResult.Result != AbpLoginResultType.Success)
        //                {
        //                    throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt(
        //                        loginResult.Result,
        //                        model.ProviderKey,
        //                        GetTenancyNameOrNull()
        //                    );
        //                }

        //                return new ExternalAuthenticateResultModel
        //                {
        //                    AccessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity)),
        //                    //ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds
        //                };
        //            }
        //        default:
        //            {
        //                //throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt(
        //                //    loginResult.Result,
        //                //    model.ProviderKey,
        //                //    GetTenancyNameOrNull()
        //                //);
        //            }
        //    }
        //}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="externalUser"></param>
        /// <returns></returns>
        //private async Task<MyIdentityUser> RegisterExternalUserAsync(ExternalAuthUserInfo externalUser)
        //{
        //    return null;
        //var user = await _userRegistrationManager.RegisterAsync(
        //    externalUser.Name,
        //    externalUser.Surname,
        //    externalUser.EmailAddress,
        //    externalUser.EmailAddress,
        //    //Authorization.Users.MyIdentityUser.CreateRandomPassword(),
        //    true
        //);

        //user.Logins = new List<MyIdentityUser>
        //{
        //    new MyIdentityUser
        //    {
        //        LoginProvider = externalUser.Provider,
        //        ProviderKey = externalUser.ProviderKey,
        //        TenantId = user.TenantId
        //    }
        //};

        //await CurrentUnitOfWork.SaveChangesAsync();

        //return user;
        // }

        //private async Task<ExternalAuthUserInfo> GetExternalUserInfo(ExternalAuthenticateModel model)
        //{
        //    var userInfo = await _externalAuthManager.GetUserInfo(model.AuthProvider, model.ProviderAccessCode);
        //    if (userInfo.ProviderKey != model.ProviderKey)
        //    {
        //        throw new UserFriendlyException("CouldNotValidateExternalUser");
        //    }

        //    return userInfo;
        //}

        //private string GetTenancyNameOrNull()
        //{
        //    if (!AbpSession.TenantId.HasValue)
        //    {
        //        return null;
        //    }

        //    return _tenantCache.GetOrNull(AbpSession.TenantId.Value)?.TenancyName;
        //}
        //}
    }
}
